import { login, getUserInfo, getUserInfoById } from '@/api/user.js'
import { setToken, getToken, removeToken, setTokenTime } from '@/utils/auth'

const state = {
  token: getToken(),
  userInfo: {}
}
const mutations = {
  setToken(state, payload) {
    state.token = payload
    setToken(payload)
  },
  getUserInfo(state, payload) {
    state.userInfo = payload
  },
  // 点击退出登录清除token和用户信息
  logout(state) {
    state.token = ''
    state.userInfo = {}
    removeToken()
  }
}
const actions = {
  // 登录请求
  async login(context, payload) {
    const res = await login(payload)
    // 往本地存储时间戳
    setTokenTime()
    context.commit('setToken', res)
  },
  // 获取用户信息
  async getUserInfo(context) {
    const res = await getUserInfo()
    const userInfo = await getUserInfoById(res.userId)
    // console.log(userInfo)
    context.commit('getUserInfo', { ...res, ...userInfo })
  }

}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

